""" 

    Location.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This script is used by the iframe located at:
    http://representedby.appspot.com/includes/gmap.html
    
    When a logged in Facebook user clicks on the map, then it updates their location 
    within the scope of RepresentedBy.  It does NOT update the location in your Facebook
    profile.
        
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
  
from utils import fbUtil, dbUtil, UserDistrict, SunlightUtil, OpenSecretsUtil, NYTimesUtil
    

class MainHandler(webapp.RequestHandler):
    
    def post(self):
        self.get()
        
    def get(self):
    
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "district":{}}
        
        try:
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, True, "location")
            if self.facebookapi is None:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "You are not logged in to Facebook."
            else:

                userDistrict = UserDistrict.get_or_insert("facebook" + str(self.facebookapi.uid), uid=int(self.facebookapi.uid), type="facebook") 
                
                lat = self.request.get("latitude", default_value=None)
                lon = self.request.get("longitude", default_value=None)

                if (lat is None) or (lon is None):
                    jsonOutput["result"] = "error"
                    jsonOutput["message"] = "You must include a valid latitude and longitude"                        
                else:
                    #get district and write it to the database
                    sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
                    districtOutput = sunlight.apicall("districts.getDistrictFromLatLong", {"latitude": lat, "longitude": lon})
                    if districtOutput is not None:
                        if districtOutput["districts"] is not None:    
                            row = {"uid": int(self.facebookapi.uid)}
                            row["state"] = districtOutput["districts"][0]["district"]["state"]
                            row["district"] = str(int(districtOutput["districts"][0]["district"]["number"]))
                            row = sunlight.getLegislatorsFromLocationRow(row)
                            jsonOutput["district"]["state"] = str.title(const.STATES[row["state"]])
                            jsonOutput["district"]["district"] = row["district"]
                            actionStr = ""
                            for key in ["rep", "jrsen", "srsen"]:
                                if row.has_key(key):
                                    jsonOutput["district"][key] = {"id": row[key]}
                                    if const.FRIENDLY_NAME.has_key(row[key]):
                                        jsonOutput["district"][key]["name"] = const.FRIENDLY_NAME[row[key]]
                                        if actionStr != "":
                                            actionStr = actionStr + ", "    
                                        actionStr = actionStr + "<a href='http://apps.facebook.com/representedby/legislator?id=" + row[key] + "'>" + const.FRIENDLY_NAME[row[key]] + "</a>"
                                else:
                                    row[key] = None        
                            dbUtil().setUserDistrict(row)
                            
                            fbStory = {"legislators": actionStr}
                            self.facebookapi.feed.publishUserAction("50099157770", fbStory)
                    else:
                        jsonOutput["result"] = "error"
                        jsonOutput["message"] = "There was an error getting your district.  Try again."
                        
        except facebook.FacebookError, e:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = str(e.msg)
                       
        self.response.out.write(simplejson.dumps(jsonOutput)) 

def main():
    application = webapp.WSGIApplication([('/fb/updatelocation', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
